import Token

# 定义二元操作符集
biOpList = [Token.TokenType.PLUS, Token.TokenType.MINUS, Token.TokenType.MUL,
            Token.TokenType.DIV, Token.TokenType.POWER]


class ExprNode:
    def __init__(self, operator):
        self.operator = operator
        # 二元运算符类型，左右子节点
        if self.operator in biOpList:
            self.left = None
            self.right = None
        # 函数类型，函数指针+单子节点
        elif self.operator == Token.TokenType.FUNC:
            self.funcPtr = None
            self.son = None
        self.value = None

    # 字符串转换,含重写
    def __str__(self):
        return str(self.operator)

    # 不同操作符运算不同
    def eval(self):
        if self.operator == Token.TokenType.PLUS:
            self.value = self.right.value + self.left.value
        elif self.operator == Token.TokenType.MINUS:
            self.value = self.left.value - self.right.value
        elif self.operator == Token.TokenType.MUL:
            self.value = self.right.value * self.left.value
        elif self.operator == Token.TokenType.DIV:
            if self.right.value != 0:
                self.value = self.left.value / self.right.value
        elif self.operator == Token.TokenType.POWER:
            self.value = self.left.value ** self.right.value
        elif self.operator == Token.TokenType.FUNC:
            v = self.son.value
            fp = self.funcPtr(v)
            self.value = fp
        return self.value
